from PyQt4.QtCore import *
from PyQt4.QtSql import *

class Utility(QObject):
    def __init__(self,  dbConn=None):
        self.skr = QDateTime()
        self.db = dbConn        
        if self.db.isOpen():
            self.idModel = QSqlTableModel()
            self.idModel.setTable("master_nodok")
            self.idModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
    def getServerToday(self):
        query = QSqlQuery(self.db)
        query.exec_("select current_timestamp from master_user")
        while query.next():
            self.skr = query.value(0).toDateTime()
        return self.skr
        
    def setDBParm(self):
        self.db.setUserName("hardi")
        self.db.setPassword("mtsbede")
#        self.db.setUserName("root")
#        self.db.setPassword("mtsbede")
        return self.db
        
    def getNewId(self,  kode,  per,  namatab):
        noAkhir = 0
        self.idModel.setFilter("kode_dok = '"+kode+"' and periode = '"+per+"'")
        self.idModel.select()      
        class DatabaseError(Exception): pass
        rback = False
        try:
            if not QSqlDatabase.database().transaction():
                raise DatabaseError
            rback = True
            if self.idModel.rowCount() == 1:
                record = self.idModel.record(0)
                noAkhir = record.value(2).toInt()[0]
                noAkhir += 1
                self.idModel.setData(self.idModel.index(0, 2), QVariant(noAkhir))
            else:
                self.idModel.insertRow(0)
                self.idModel.setData(self.idModel.index(0, 0), QVariant(kode))
                self.idModel.setData(self.idModel.index(0, 1), QVariant(per))
                self.idModel.setData(self.idModel.index(0, 2), QVariant("1"))
                self.idModel.setData(self.idModel.index(0, 3), QVariant(namatab))
                noAkhir = 1
            self.idModel.submitAll()
            if not QSqlDatabase.database().commit():
                raise DatabaseError
            rback = False
        finally:
            if rback:
                if not QSqlDatabase.database().rollback():
                    raise DatabaseError
        return noAkhir
